package cn.ug.msg.web.controller;

import cn.ug.bean.base.SerializeObject;
import cn.ug.bean.type.ResultType;
import cn.ug.core.SerializeObjectError;
import cn.ug.msg.bean.SmsBean;
import cn.ug.msg.service.SmsService;
import cn.ug.msg.web.utils.HttpClientUtil;
import cn.ug.msg.web.utils.TemplateUtil;
import cn.ug.util.UF;
import cn.ug.web.controller.BaseController;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static cn.ug.config.QueueName.QUEUE_MSG_SMS_SEND;
import static org.springframework.web.bind.annotation.RequestMethod.GET;
import static org.springframework.web.bind.annotation.RequestMethod.POST;

@RestController
@RequestMapping("sms")
public class SmsController extends BaseController {
    private static final String SMS_SIGN_NAME = "【柚子黄金】";
    private ObjectMapper mapper = new ObjectMapper();

    @Resource
    private SmsService smsService;

    @Resource
    private AmqpTemplate amqpTemplate;
    @Value("${zhuanxinyun.sms.url}")
    private String url;
    @Value("${zhuanxinyun.sms.appKey}")
    private String appKey;
    @Value("${zhuanxinyun.sms.appSecret}")
    private String appSecret;
    /**
     * 测试
     */
    @RequestMapping(value = "test", method = GET)
    public SerializeObject test() throws JsonProcessingException {
        SmsBean smsBean = new SmsBean();
        smsBean.setPhone("18868717896");
        smsBean.setType("SMS_122292632");

        Map<String, String> paramMap = new HashMap<>(1);
        paramMap.put("code", UF.getRandomUUID().substring(0, 5));
        smsBean.setParamMap(paramMap);

        amqpTemplate.convertAndSend(QUEUE_MSG_SMS_SEND, mapper.writeValueAsString(smsBean));

        return new SerializeObject<>(ResultType.NORMAL);
    }

    @RequestMapping(value = "test02", method = GET)
    public SerializeObject test02() throws JsonProcessingException {
        List<NameValuePair> nvps = new ArrayList<NameValuePair>();
        nvps.add(new BasicNameValuePair("appKey", appKey));
        nvps.add(new BasicNameValuePair("appSecret", appSecret));
        nvps.add(new BasicNameValuePair("phones", "13094818226"));
        nvps.add(new BasicNameValuePair("content", "【柚子黄金】尊敬的用户：您已参与猜金价活动，您在此期间获得的10.2%福利券会在24小时内发送至您账户，请在APP内查收哦。"));
        String data = HttpClientUtil.invokeHttp(url, nvps);

        return new SerializeObject<>(ResultType.NORMAL, data);
    }
    /**
     * 发送短信
     * @param entity		    记录集
     * @return				    是否操作成功
     */
    @RequestMapping(method = POST)
    public SerializeObject send(@RequestBody SmsBean entity) {
        if(null == entity || StringUtils.isBlank(entity.getPhone()) || StringUtils.isBlank(entity.getType())) {
            return new SerializeObjectError("00000002");
        }
        // 0:操作成功 1：操作失败 2：触发短信太频繁（触发分钟级流控）3:非法手机号
        int val = smsService.send(entity);
        if(val != 0) {
            getLog().error("阿里短信发送失败");
            String content = TemplateUtil.REGISTER.replaceAll("#content#",entity.getParamMap().get("code"));
            List<NameValuePair> nvps = new ArrayList<NameValuePair>();
            nvps.add(new BasicNameValuePair("appKey", appKey));
            nvps.add(new BasicNameValuePair("appSecret", appSecret));
            nvps.add(new BasicNameValuePair("phones", entity.getPhone()));
            nvps.add(new BasicNameValuePair("content", SMS_SIGN_NAME+content));
            String data = HttpClientUtil.invokeHttp(url, nvps);
            getLog().info("专信云短信发送结果：" + data);
            if (StringUtils.isNotBlank(data)) {
                JSONObject result = JSONObject.parseObject(data);
                String errorCode = result.getString("errorCode");
                if (StringUtils.equals(errorCode, "000000")) {
                    return new SerializeObject(ResultType.NORMAL, "19000101");
                }
            }
        } else {
            return new SerializeObject(ResultType.NORMAL, "19000101");
        }

        /*if(val == 0) {
            return new SerializeObject(ResultType.NORMAL, "19000101");
        } else if(val == 2) {
            return new SerializeObjectError("19000103");
        } else if(val == 3) {
            return new SerializeObjectError("19000104");
        }*/
        // 发送失败
        return new SerializeObjectError("19000102");
    }

}
